package a66weding.com.jiehuntong.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.toolsbudget.BaseBudgetActivity;
import a66weding.com.jiehuntong.beans.ItemTypeBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.view.MyFlowLayout;
import a66weding.com.jiehuntong.view.MyGridview;
import a66weding.com.jiehuntong.widgets.quicksearchlist.CityAdapter;
import a66weding.com.jiehuntong.widgets.quicksearchlist.CityData;
import a66weding.com.jiehuntong.widgets.quicksearchlist.CityItem;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactItemComparator;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactItemInterface;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactListViewImpl;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactsSectionIndexer;
import a66weding.com.jiehuntong.widgets.quicksearchlist.QuickIndexView;

public class SearchCityActivity extends CommonActivity  implements TextWatcher, QuickIndexView.OnIndexChangeListener, View.OnClickListener {
    private EditText mSearchEt;
    private QuickIndexView mIndexView;
    private ListView mMainListView;
    private TextView mSearchEmptyTv;
    private RelativeLayout mSearchEmptyRlay;
    private LinearLayout mBackLay;
    private RelativeLayout mQuickIndexRlay;

    private TextView tv_main;

    private String searchString;

    private Object searchLock = new Object();
    boolean inSearchMode = false;

    List<ContactItemInterface> contactList;
    List<ContactItemInterface> filterList;

    private ArrayList<ItemTypeBean> itemTypeList;

    private MyCityAdapter mLvAdapter;
    private String[] mHotCities;

    private static final int SEARCHRESULTSUCESS=1;
    private static final int SEARCHRESULTFAIL=2;

    private String cityName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_search_city);

        Intent intent = getIntent();
        if(intent!=null) {
            cityName=  intent.getStringExtra("city");
        }

        initView();
        initData();
    }


    public void initView() {


        mSearchEt = (EditText) findViewById(R.id.et_search);
        mIndexView = (QuickIndexView)findViewById(R.id.qiv_sideBar);
        mMainListView = (ListView) findViewById(R.id.lv_tools_wedreg_citylist);
        mSearchEmptyTv = (TextView) findViewById(R.id.search_empty);
        mSearchEmptyRlay = (RelativeLayout) findViewById(R.id.rlay_tools_wedregcity);
        mBackLay = (LinearLayout) findViewById(R.id.llay_tools_wedregister_back);
        mQuickIndexRlay = (RelativeLayout)findViewById(R.id.side_layout);


        mSearchEt.addTextChangedListener(this);
        mIndexView.setOnIndexChangeListener(this);
        mBackLay.setOnClickListener(this);




    }



    public void initData() {


        itemTypeList=new ArrayList<ItemTypeBean>();
        mHotCities = new String[]
                { "北京", "上海", "杭州", "西安", "成都", "深圳",
                        "广州", "武汉", "南京", "重庆", "天津",
                        "苏州", "厦门", "三亚" };

        filterList = new ArrayList<ContactItemInterface>();
        contactList=  CityData.getSampleContactList();
        filterList.clear();
        for (ContactItemInterface item : contactList) {
            filterList.add(item);
        }
        ItemTypeBean itemType=null;
        for (int i = 0; i < filterList.size()+1; i++) {
            if(i==0) {
                itemType=  new ItemTypeBean(0,0,"letterheader");
            }else{
                itemType=  new ItemTypeBean(i,1,"letteritem");
            }
            itemTypeList.add(itemType);

        }

        if(itemTypeList!=null && itemTypeList.size()>0 && filterList!=null) {
            mLvAdapter=new MyCityAdapter(itemTypeList,filterList);
            mMainListView.setAdapter(mLvAdapter);

        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llay_tools_wedregister_back:
               finish();
                break;
            case R.id.infoRowContainer://点击城市
                ContactItemInterface item = (ContactItemInterface) view.getTag();
                mSearchEt.setText("");
                // 获取启动该Activity的上一个Activity对应的Intent
                Intent intent = getIntent();
                intent.putExtra("city", item.getDisplayInfo());

                // 设置SecondActivity的结果码(resultCode)，并设置在当前结束后退回去的Activity
                this.setResult(BaseBudgetActivity.GETPLACERESULTCODE, intent);
                this.setResult(MainActivity.getResultForHomecity, intent);

                finish();

                break;
            case R.id.btn_hotcity:
                String cityName = (String) view.getTag();
                Intent intent2 = getIntent();
                intent2.putExtra("city", cityName);

                // 设置SecondActivity的结果码(resultCode)，并设置在当前结束后退回去的Activity
                this.setResult(BaseBudgetActivity.GETPLACERESULTCODE, intent2);
                finish();

                break;

        }
    }


    public class MyCityAdapter extends BaseAdapter {
        private List<ItemTypeBean>  typeList;
        private int resource; // store the resource layout id for 1 row
        private boolean inSearchMode = false;
        private List<ContactItemInterface> _items;

        private ContactsSectionIndexer indexer = null;



        public MyCityAdapter(List<ItemTypeBean> typeList,List<ContactItemInterface> _items){
            this.typeList=typeList;

            Collections.sort(_items, new ContactItemComparator());

            setIndexer(new ContactsSectionIndexer(_items));
        }


        @Override
        public int getCount() {
            return typeList.size();
        }

        @Override
        public int getViewTypeCount() {
            return typeList.size();
        }

        @Override
        public int getItemViewType(int position) {
            return typeList.get(position).getType();
        }

        @Override
        public Object getItem(int position) {
            return typeList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            int type = typeList.get(position).getType();
            ViewHolder myHolder=null;
            switch (type) {
                case 0:
                    if(convertView==null) {
                        myHolder=new ViewHolder();
                        convertView= View.inflate(SearchCityActivity.this, R.layout.item_header_citylist, null);

                        myHolder.mCurrentCityBtn = (Button) convertView.findViewById(R.id.btn_currentcity);
                        myHolder.mHotCityGv = (MyGridview) convertView.findViewById(R.id.gview_tools_wedreg_hotcity);

                        convertView.setTag(myHolder);
                    }else{
                        myHolder= (ViewHolder) convertView.getTag();
                    }
                    myHolder.mCurrentCityBtn.setText(cityName);
                    final List<String> hotCities = Arrays.asList(mHotCities);
                    myHolder.mHotCityGv.setAdapter(new CommonAdapter<String>(SearchCityActivity.this,hotCities,R.layout.item_city_view ) {
                        @Override
                        public void convert(MyViewHolder holder, int position) {

                            Button cityBtn = (Button) holder.getView(R.id.btn_hotcity);
                            cityBtn.setText(hotCities.get(position));
                            cityBtn.setTag(cityBtn.getText().toString());
                            cityBtn.setOnClickListener(SearchCityActivity.this);

                        }
                    });

                    break;
                case 1:
                    myHolder=new ViewHolder();
                    ContactItemInterface item = filterList.get(position-1);
                    if(convertView==null) {
                        convertView= View.inflate(SearchCityActivity.this, R.layout.city_item, null);

                        myHolder.mCityNameTv= (TextView) convertView.findViewById(R.id.cityName);

                        myHolder.mSectionTv= (TextView) convertView.findViewById(R.id.sectionTextView);
                        myHolder.mSectionRlay= (RelativeLayout) convertView.findViewById(R.id.infoRowContainer);

                        convertView.setTag(myHolder);
                    }else{
                        myHolder= (ViewHolder) convertView.getTag();
                    }
                    myHolder.mSectionRlay.setTag(item);
                    myHolder.mSectionRlay.setOnClickListener(SearchCityActivity.this);

                    if(filterList!=null && filterList.size()>0) {


                        showSectionViewIfFirstItem( myHolder.mSectionTv, item, position-1);

                        populateDataForRow(myHolder.mCityNameTv, item, position-1);

                    }
                    break;
            }


            return convertView;
        }



        public void populateDataForRow(TextView parentView, ContactItemInterface item,
                                       int position)
        {
            View infoView = parentView.findViewById(R.id.infoRowContainer);

            parentView.setText(item.getDisplayInfo());
        }

        public void showSectionViewIfFirstItem(View rowView,
                                               ContactItemInterface item, int position)
        {
            TextView sectionTextView = (TextView) rowView;

            if (inSearchMode)
            {
                sectionTextView.setVisibility(View.GONE);
            } else
            {

                if (indexer.isFirstItemInSection(position))
                {

                    String sectionTitle = indexer.getSectionTitle(item
                            .getItemForIndex());
                    sectionTextView.setText(sectionTitle);
                    sectionTextView.setVisibility(View.VISIBLE);

                } else
                    sectionTextView.setVisibility(View.GONE);
            }
        }



        public ContactsSectionIndexer getIndexer()
        {
            return indexer;
        }

        public void setIndexer(ContactsSectionIndexer indexer)
        {
            this.indexer = indexer;
        }

        public boolean isInSearchMode()
        {
            return inSearchMode;
        }

        public void setInSearchMode(boolean inSearchMode)
        {
            this.inSearchMode = inSearchMode;
        }



        class ViewHolder {
            MyGridview mHotCityGv;
            Button mCurrentCityBtn;
            ContactListViewImpl mCityLv;
            TextView mLvtopTv;
            MyFlowLayout mHotCityLay;

            TextView mCityNameTv;
            TextView mSectionTv;
            RelativeLayout mSectionRlay;

        }



    }



    @Override
    public void onIndexChanged(final String word) {
        if(!TextUtils.isEmpty(word)) {

            searchcity2(word);
        }

    }

    @Override
    public void onTouchUp() {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        searchString = mSearchEt.getText().toString().trim().toUpperCase();

        mSearchEmptyTv.setVisibility(View.GONE);
        mSearchEmptyRlay.setVisibility(View.VISIBLE);

        if(TextUtils.isEmpty(searchString)) {
            filterList.clear();
            for (ContactItemInterface item : contactList) {
                filterList.add(item);
            }

            ItemTypeBean itemType=null;
            for (int i = 0; i < filterList.size()+1; i++) {
                if(i==0) {
                    itemType=  new ItemTypeBean(0,0,"letterheader");
                }else{
                    itemType=  new ItemTypeBean(i,1,"letteritem");
                }
                itemTypeList.add(itemType);

            }

            if(itemTypeList!=null && itemTypeList.size()>0 && filterList!=null) {
                mLvAdapter=new MyCityAdapter(itemTypeList,filterList);
                mMainListView.setAdapter(mLvAdapter);

            }

            mQuickIndexRlay.setVisibility(View.VISIBLE);


        }else {

            new Thread(){
                @Override
                public void run() {
                    mHandler.removeCallbacksAndMessages(null);
                    searchcity(searchString);
                }
            }.start();
        }

    }





    public void searchcity(String word){
        inSearchMode = (word.length() > 0);
        filterList.clear();
        if (inSearchMode) {

            for (ContactItemInterface item : contactList) {
                CityItem contact = (CityItem) item;
                boolean isPinyin = contact.getFullName().toUpperCase().indexOf(word) > -1;
                boolean isChinese = contact.getNickName().contains(word);

                if (isPinyin || isChinese)
                {
                    filterList.add(item);

                }
            }
            if(filterList.size()>0){
                mHandler.sendEmptyMessage(SEARCHRESULTSUCESS);
            }else{
                mHandler.sendEmptyMessage(SEARCHRESULTFAIL);
            }

        }

    }



    public void searchcity2(String word){
        inSearchMode = (word.length() > 0);
        if (inSearchMode) {

            int sectionIndex = mLvAdapter.getIndexer().getSectionIndex(word);
            int positionForSection = mLvAdapter.getIndexer().getPositionForSection(sectionIndex);

            mMainListView.setSelection(positionForSection);

            String slecStr = filterList.get(positionForSection).getDisplayInfo();

        }

    }




    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SEARCHRESULTSUCESS:
                    if (inSearchMode) {

                        if(filterList!=null) {
                            CityAdapter adapter = new CityAdapter(SearchCityActivity.this,R.layout.city_item, filterList);

                            mMainListView.setAdapter(new CommonAdapter<ContactItemInterface>(SearchCityActivity.this,filterList,R.layout.city_item) {

                                @Override
                                public void convert(MyViewHolder holder, int position) {
                                    ContactItemInterface contactItemInterface = filterList.get(position);
                                    String displayInfo = contactItemInterface.getDisplayInfo();
                                    RelativeLayout cityRlay = (RelativeLayout) holder.getView(R.id.infoRowContainer);

                                    cityRlay.setTag(contactItemInterface);
                                    cityRlay.setOnClickListener(SearchCityActivity.this);

                                    holder.setText(R.id.cityName,displayInfo);

                                }
                            });


                        }

                        mQuickIndexRlay.setVisibility(View.GONE);
                    }
                    break;
                case SEARCHRESULTFAIL:
                    mSearchEmptyTv.setVisibility(View.VISIBLE);
                    mSearchEmptyRlay.setVisibility(View.GONE);
                    mQuickIndexRlay.setVisibility(View.GONE);

                    break;
            }
        }
    };
}
